<?php

namespace app\api\controller;

use think\Request;
use think\Db;

class Users extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function info()
    {
        $header = Request::instance()->param();
        $authKey = $header['token'];
        //$sessionId = $header['sessionid'];
        $cache = cache('Auth_' . $authKey);
        // 检查账号有效性
        $userInfo = $cache['userInfo'];
        if (!$userInfo) {
            return resultArray(['code' => 104, 'error' => '用户信息失效']);
        }
        //$userInfo['role'] = ['admin'];
        return resultArray(['data' => $userInfo]);
    }


    /**
     * 用户列表
     */
    public function index()
    {
        $param = $this->param;
        $page = !empty($param['page']) ? $param['page'] - 1 : 0;
        $limit = !empty($param['row']) ? $param['row'] : 10;
        $count = Db::name('admin_user')->count('id');
        $list = Db::name('admin_user')
            ->alias('a')
            ->join('admin_group b', 'a.user_group = b.id')
            ->field('a.*,b.title')
            ->limit($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $key => &$value) {
                $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                unset($value['password']);
                unset($value['realname']);
                unset($value['structure_id']);
                unset($value['post_id']);
                unset($value['last_login']);
                unset($value['ip']);
                unset($value['overtime']);
                if ($value['photo']) {
                    $value['photo'] = config('http.port') . '/api/public/upload/img/' . $value['photo'];
                }
            }
        }
        $return['total'] = $count;
        $return['totalPage'] = ceil($count / $limit);
        $return['list'] = $list;
        // var_dump($return);
        return resultArray(['data' => $return]);
    }


    /**
     * 用户名搜索用户
     */
    public function search()
    {
        $param = $this->param;
        $page = !empty($param['page']) ? $param['page'] - 1 : 0;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $where = array();
        $where['a.username|a.phone|a.email'] = array('like', '%' . $param['content'] . '%');
        $count = Db::name('admin_user')->alias('a')->where($where)->count('id');
        $list = Db::name('admin_user')
            ->alias('a')
            ->where($where)
            ->join('admin_group b', 'a.user_group = b.id')
            ->field('a.*,b.title')
            ->limit($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $key => &$value) {
                $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                unset($value['password']);
                unset($value['realname']);
                unset($value['structure_id']);
                unset($value['post_id']);
                unset($value['last_login']);
                unset($value['ip']);
                unset($value['overtime']);
                if ($value['photo']) {
                    $value['photo'] = config('http.port') . '/api/public/upload/img/' . $value['photo'];
                }
            }
        }
        $return['count'] = $count;
        $return['list'] = $list;
        return resultArray(['data' => $return]);
    }



    /**
     * 获取用户信息
     */
    public function userInfo()
    {
        $param = $this->param;
        $user = Db::name('admin_user');
        $res = $user->where(['id' => $param['id']])->find();
        if (!$res) {
            return resultArray(['error' => '用户不存在']);
        }
        if ($res['photo']) {
            $res['photo'] = config('http.port') . '/api/public/upload/img/' . $res['photo'];
        }
        return resultArray(['data' => $res]);
    }




    public function photoUpload()
    {
        header("Access-Control-Allow-Origin: *");
        if (!empty($_FILES)) {
            $stored_path = 'upload/img/' . time() . '_' . $_FILES['file']['name'];
            if (move_uploaded_file($_FILES['file']['tmp_name'], $stored_path)) {
                $path = config('http.port');
                return resultArray(['data' => time() . '_' . $_FILES['file']['name']]);
            } else {
                return resultArray(['error' => '文件上传失败']);
            }
        } else {
            return resultArray(['error' => '请选择文件']);
        }
    }



    /**
     * 新增用户
     */
    public function save()
    {
        $param = $this->param;
        $user = Db::name('admin_user');
        $username = trim($param['username']);
        $phone = trim($param['phone']);
        $email = trim($param['email']);
        $nickname = $param['nickname'];
        if (!empty($username)) {
            $find = $user->where(['username' => $username])->find();
            if ($find) {
                return resultArray(['error' => '用户名已存在', 'code' => 1002]);
            }
        }
        if (empty($phone) && empty($email)) {
            return resultArray(['error' => '电话邮箱不能全部为空', 'code' => 1003]);
        }
        if ($phone) {
            if (!preg_match("/^1[345789]\d{9}$/", $phone)) {
                return resultArray(['error' => '手机号格式不正确', 'code' => 1004]);
            }
            if ($user->where(['phone' => $phone])->find()) {
                return resultArray(['error' => '手机号已存在', 'code' => 1005]);
            }
        }
        if ($email) {
            $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
            if (!preg_match($pattern, $email)) {
                return resultArray(['error' => '邮箱格式不正确', 'code' => 1006]);
            }
            if ($user->where(['email' => $email])->find()) {
                return resultArray(['error' => '邮箱已存在', 'code' => 1007]);
            }
        }
        $data['username'] = $username;
        $data['phone'] = $phone;
        $data['email'] = $email;
        $data['nickname'] = $nickname;
        $data['password'] = user_md5($param['password']);
        $data['remark'] = $param['remark'];
        $data['status'] = $param['status'];
        $data['user_group'] = $param['user_group'];
        $data['photo'] = $param['photo'];
        $data['create_time'] = time();
        $data['update_time'] = time();
        Db::startTrans();
        $res = $user->insertGetId($data);
        Db::table('rszh_admin_access')->insert(array('user_id' => $res, 'group_id' => $param['user_group']));
        if ($res) {
            $url = config('http.url') . '/api/v2/user/register?appId=beb7da4ced7c42a085c3c99697f9aa42&secretKey=3949ba59abbe56e057f20f883eadce&phone=' . $phone . '&nickname=' . $nickname . '&pwd=' . md5($param['password']) . '&email=' . $email . '&account=' . $username;
            $return_str = curl_get($url);
            $return_arr = json_decode($return_str, 1);
            // var_dump($return_arr);
            if ($return_arr['code'] == 200) {
                $up_data['suid'] = $return_arr['data']['suid'];
                $res_uid = $user->where(['id' => intval($res)])->update($up_data);
                if ($res_uid) {
                    Db::commit();
                    if (!empty($param['photo'])) {
                        $this->addFaceUser(intval($res), $param['photo']);
                    }
                    return  resultArray(['data' => '添加用户成功']);
                } else {
                    Db::rollback();
                    return  resultArray(['error' => '操作失败']);
                }
            } else {
                Db::rollback();
                return  resultArray(['error' => '添加失败' . $return_arr['code']]);
            }
        }
        Db::rollback();
        return  resultArray(['error' => '添加用户失败']);
    }



    /**
     * 更新用户信息
     */
    public function update()
    {
        $param = $this->param;
        $user = Db::name('admin_user');
        $id = intval($param['id']);
        $username = trim($param['username']);
        $phone = trim($param['phone']);
        $email = trim($param['email']);
        $where['id'] = array('neq', $id);
        if (!empty($username)) {
            $where['username'] = $username;
            $find = $user->where($where)->find();
            if ($find) {
                return resultArray(['error' => '用户名已存在', 'code' => 1002]);
            }
        }
        $data['username'] = $username;
        if (empty($phone) && empty($email)) {
            return resultArray(['error' => '电话邮箱不能全部为空', 'code' => 1003]);
        }
        if ($phone) {
            if (!preg_match("/^1[345789]\d{9}$/", $phone)) {
                return resultArray(['error' => '手机号格式不正确', 'code' => 1004]);
            }
            $where['phone'] = $phone;
            unset($where['username']);
            if ($user->where($where)->find()) {
                return resultArray(['error' => '手机号已存在', 'code' => 1005]);
            }
        }
        $data['phone'] = $phone;
        if ($email) {
            $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
            if (!preg_match($pattern, $email)) {
                return resultArray(['error' => '手邮箱格式不正确', 'code' => 1006]);
            }
            $where['email'] = $email;
            unset($where['username']);
            unset($where['phone']);
            if ($user->where($where)->find()) {
                return resultArray(['error' => '邮箱已存在', 'code' => 1007]);
            }
        }
        $data['email']  = $email;
        $data['nickname'] = $param['nickname'];
        if (!empty($param['password'])) {
            $data['password'] = user_md5($param['password']);
        }
        $data['remark'] = $param['remark'];
        if (!empty($param['photo'])) {
            $res = $user->where(['id' => $id])->find();
            if ($res['photo']) {
                unlink('upload/img/' . $res['photo']);
            }
            $data['photo'] = $param['photo'];
        }
        $data['user_group'] = $param['user_group'];
        Db::table('rszh_admin_access')->where(array('user_id' => $id))->update(array('group_id' => $param['user_group']));
        $data['update_time'] = time();
        $res = $user->where(['id' => $id])->update($data);
        if ($res) {
            return resultArray(['data' => '修改用户成功']);
        }
        return resultArray(['error' => '修改失败']);
    }


    /**
     * 冻结&激活用户
     */
    public function statusChange()
    {
        $where['id'] = input('param.id');
        $find = Db::name('admin_user')->where($where)->find();
        if ($find) {
            $data['status'] = input('param.status');
            $res = Db::name('admin_user')->where($where)->update($data);
            return resultArray(['data' => '']);
        }
        return resultArray(['error' => '用户不存在']);
    }


    /**
     * 删除用户
     */
    public function delete()
    {
        $user = Db::name('admin_user');
        $param = $this->param;
        $where['id'] = intval($param['id']);
        $find = $user->where($where)->find();
        if ($find['photo']) {
            if (file_exists('upload/img/' . $find['photo'])) {
                unlink('upload/img/' . $find['photo']);
            }
            $this->deleteFaceUser($find['id'], $find['nickname']);
        }
        if ($find['suid']) {
            $url = config('http.url') . '/api/v2/user/delete?appId=beb7da4ced7c42a085c3c99697f9aa42&secretKey=3949ba59abbe56e057f20f883eadce&token=D24D6CD7C94AE9B0D0758C016F733CAF6134400540A6EEAC&suid=' . $find['suid'];
            $res = curl_get($url);
        }
        $data = $user->where($where)->delete();
        if (!$data) {
            return resultArray(['error' => '删除失败']);
        } else {
            return resultArray(['data' => '删除成功']);
        }
    }


    public function addFaceUser($uid, $base_url)
    {
        // $uid = 1;
        //$base_url = '1543307786_timg.jpg';
        $find = Db::name('admin_user')->where(array('id' => $uid))->find();
        $nickname = $find['nickname'];
        $base64_file = '';
        $file = './upload/img/' . $base_url;
        if (file_exists($file)) {
            $mime_type = 'jpg';
            $base64_data = base64_encode(file_get_contents($file));
            // $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
            $base64_file =  chunk_split(base64_encode(file_get_contents($file)));
        }
        //var_dump($base64_file);exit;
        $url = 'http://192.168.0.17:9901/?request=addFaceUser';
        //$post_array['picBase64'] = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
        $data['userId'] = trim($uid);
        //$data['nickname'] = $nickname;
        $data['userInfo'] = $nickname;
        $data['picBase64'] = $base64_file;
        $res = curl_post($url, json_encode($data));
    }




    public function updateFaceUser($uid, $base_url)
    {
        // $uid = 1;
        //$base_url = '1543307786_timg.jpg';
        $find = Db::name('admin_user')->where(array('id' => $uid))->find();
        $nickname = $find['nickname'];
        $base64_file = '';
        $file = './upload/img/' . $base_url;
        if (file_exists($file)) {
            $mime_type = 'jpg';
            $base64_data = base64_encode(file_get_contents($file));
            // $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
            $base64_file = chunk_split(base64_encode(file_get_contents($file)));
        }
        //var_dump($base64_file);exit;
        $url = 'http://192.168.0.17:9901/?request=updateFaceUser';
        //$post_array['picBase64'] = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
        $data['userId'] = trim($uid);
        //$data['nickname'] = $nickname;
        $data['userInfo'] = $nickname;
        $data['picBase64'] = $base64_file;
        $res = curl_post($url, json_encode($data));
    }




    public function deleteFaceUser($uid, $name)
    {
        //$uid = 1;
        $url = 'http://192.168.0.17:9901/?request=deleteFaceUser';
        $data['userId'] = $uid;
        $data['userInfo'] = $name;
        $res = curl_post($url, json_encode($data));
    }



    /**
     * 获取会议人脸照片列表
     */
    public function getPicInfo()
    {
        $param = $this->param;
        $page = !empty($param['page']) ? $param['page'] - 1 : 0;
        $limit = !empty($param['rows']) ? $param['rows'] : 10;
        $where['photo'] = array('exp', 'is not null');
        $count = Db::name('admin_user')->where($where)->count('id');
        $list = Db::name('admin_user')
            ->where($where)
            ->field('id,nickname,photo')
            ->limit($page, $limit)
            ->select();
        if ($list) {
            foreach ($list as $key => &$value) {
                $value['userId'] = trim($value['id']);
                $file = './upload/img/' . $value['photo'];
                if (file_exists($file)) {
                    $mime_type = 'jpg';
                    $base64_data = base64_encode(file_get_contents($file));
                    // $value['base64_file'] = 'data:'.$mime_type.';base64,'.$base64_data;
                    $value['base64_file'] =  chunk_split(base64_encode(file_get_contents($file)));
                    unset($value['photo']);
                    unset($value['id']);
                }
            }
        }
        $return['total'] = $count;
        $return['list'] = $list;
        return resultArray(['data' => $return]);
    }

    /**
     * 获取会议人脸照片总数
     */
    public function getPicsNum()
    {
        $param = $this->param;
        $count = Db::name('admin_user')->where($where)->count('id');
        $return['total'] = $count;

        return resultArray(['data' => $return]);
    }



    /**
     * 接受签到信息
     */
    public function recvSignInfo()
    {
        $param = $this->param;
        $userId = intval($param['userId']);
        $nickname = $param['nickname'];
        $meetingId = intval($param['meetingId']);
        $meetingName = $param['meetingName'];
        $meeting = Db::name('meeting_list')->where(['cid' => $meetingId, 'name' => $meetingName])->find();
        if ($meeting) {
            $user = Db::name('admin_user')->where(['id' => $userId, 'nickname' => $nickname])->find();
            if ($user) {
                if ($user['photo']) {
                    Db::name('admin_user')->insert(['meeting_id' => $meetingId, 'user_id' => $userId, 'nickname' => $nickname]);
                    $return['photo'] = $user['photo'];
                    return resultArray(['data' => $return]);
                }
                return resultArray(['error' => '该用户暂无图片']);
            }
            return resultArray(['error' => '用户不存在']);
        }
        return resultArray(['error' => '会议不存在']);
    }

    /**
     *  按照部门id查询所有子部门及其下人员
     *  参数
     *  dptid 部门id
     *  status 用户状态
     *  limit 每页数量 
     *  page  页数  
     */
    public function childDepartmentUsers($start_time = "0", $end_time = "9999999999", $match = "", $limit = '10', $page = '1')
    {
        //接收父部门信息
        $dptid = input('param.dptid');
        $limit = input('param.limit') ? input('param.limit') : $limit;
        $page = input('param.page') ? input('param.page') : $page;
        $status = input('param.status');
        //此处为时间模糊匹配使用
        if (!$start_time || !$end_time) {
            //有参数为空
            $start_time = 0;
            $end_time = 9999999999;
        } else if ($start_time == $end_time) {
            //同天查询，结束时间加一天
            $end_time += 86400;
        }
        //此处为模糊匹配固定字段使用
        $match = input('param.match') ? input('param.match') : $match;
        try {
            //查询父部门信息，生成父部门编号
            $result = Db::name('department')->where(['dptid' => $dptid])->find();
            $num = $result['num'];
            //指定查询属性
            $filter = ['id', 'username', 'dptid', 'title', 'u.update_time', 'user_group', 'status'];
            //按部门连接user表和department表
            $data = Db::name('department')
                ->alias('d')
                ->join('admin_user u', 'd.dptid = u.structure_id')
                ->where(['status' => $status])
                ->where('num', 'like', $num . '%')
                //时间戳模糊匹配
                ->where('u.update_time', 'between', [$start_time, $end_time])
                //模糊匹配
                ->where('username|title', 'like', '%' . $match . '%')
                ->field($filter)
                ->limit($limit)
                ->page($page)
                ->order('structure_id')
                ->select();
            //var_dump($data);die;
            //查询所有结果总数
            $total = Db::name('department')
                ->alias('d')
                ->join('admin_user u', 'd.dptid = u.structure_id')
                ->where(['status' => $status])
                ->where('num', 'like', $num . '%')
                //时间戳模糊匹配
                ->where('u.update_time', 'between', [$start_time, $end_time])
                //模糊匹配
                ->where('username|title', 'like', '%' . $match . '%')
                ->count();
            //用户状态数组
            $status_detail = ['冻结', '正常'];
            $group_detail = [1 => '管理员', 4 => '普通用户'];
            foreach ($data as $key => $value) {
                $data[$key]['update_time'] = date('Y-m-d H:i:m', $value['update_time']);
                $data[$key]['detail'] = $status_detail[$value['status']];
                $data[$key]['group_detail'] = $group_detail[$value['user_group']];
            }
            //return resultArray(['data' => $data]);
            $result = [
                'list' => $data,
                'total' => $total,
                'total_page' => ceil($total / $limit)
            ];
            return resultArray(['data' => $result]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 按群组进行匹配日期和关键词的人员列表
     */
    public function list($start_time = 0, $end_time = 9999999999, $match = "", $limit = '10', $page = '1')
    {
        $map = [
            'status' => isset($this->param['status'])?$this->param['status'] : ['in','0,1'],
            'a.update_time' => ['between', [$start_time?$start_time : 0, $end_time ? $end_time : 9999999999]],
            //模糊匹配
            'username' => ['like', '%' . trim($match) . '%'],
            //默认去除超级管理员
            'a.id' => array('neq', 1),
            //默认去除公共api用户
            'a.username' => array('neq', 'publicapi'), 
        ];
        $user_model = Model('User');
        if(input('param.dptid'))
        {
            $map['did'] =  input('param.dptid');
            $result = $user_model->getListWithDptByDid($map,$limit,$page);
        }else{
            $result = $user_model->getListWithDptByDid($map,$limit,$page);
        }
        return resultArray(['data' => $result]);
    }

    /**
     * 简单人员列表
     */
    public function listArray()
    {
        $map = [
            //'status' => 1,
        ];
        $user_model = Model('User');
        if(input('param.dptid'))
        {
            $map['did'] =  input('param.dptid');
            // 默认除去超级管理员
            //'a.id' => array('neq', 1), 
        }
        $map['id'] = array('neq', 1);
        $result = $user_model->where($map)->field('id,username')->select();
        return resultArray(['data' => ['list' => $result]]);
    }

    /**
     * 添加新用户
     */
    public function add()
    {
        //$param = $this->param;
        $param = input('param.');
        $user = Db::name('admin_user');
        $username = trim($param['username']);
        if (!preg_match('/^[@_.A-Za-z0-9]{4,20}+$/', $username)) {
            return resultArray(['error' => '用户名格式错误', 'code' => 201]);
        }
        if(!preg_match('/^[a-zA-Z0-9]{4,20}$/', trim($param['password']))) {
            return resultArray(['error' => '密码格式错误', 'code' => 201]);
        }
        if (!empty($username)) {
            $find = $user->where(['username' => $username])->find();
            if ($find) {
                return resultArray(['error' => '用户名已存在', 'code' => 1002]);
            }
        }
        $data['username'] = $username;
        $data['password'] = user_md5($param['password']);
        $data['status'] = $param['status']?:1;
        $data['user_group'] = $param['user_group']?:4;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $data['nickname'] = $param['nickname']?:'';
        $data['phone'] = $param['phone']?:'';

        $user_group = $GLOBALS['userInfo']->user_group;
        if($user_group->id != 1 && $user_group == $param['user_group']){
            return  resultArray(['error' => '没有权限添加管理员']);
        }

        Db::startTrans();
        try {
            $res = $user->insertGetId($data);
            Db::table('rszh_admin_access')->insert(array('user_id' => $res, 'group_id' => $param['user_group']));
            Db::commit();
            return  resultArray(['data' => '']);
        } catch (\Exception $e) {
            Db::rollback();
            return  resultArray(['error' => '添加用户失败']);
        }
    }


    /**
     * 更新用户信息
     */
    public function updates()
    {
        $param = $this->param;
        $user = Db::name('admin_user');
        $id = intval($param['id']);
        if (!preg_match('/^[@_.A-Za-z0-9]{5,20}+$/', $param['username'])) {
            return resultArray(['error' => '用户名格式错误', 'code' => 201]);
        }
        if (empty($id) || empty($param['username']) || empty($param['user_group']) || !isset($param['status'])) {
            return resultArray(['error' => '参数有空属性']);
        }
        if ($id == 1) {
            return resultArray(['error' => '不能修改超级管理员']);
        }
        if(Model('User')->get($id)->user_group != $param['user_group'] && $GLOBALS['userInfo']->id != 1){
            return resultArray(['error' => '不能修改权限']);
        }

        $data['username'] = $param['username'];
        $data['user_group'] = $param['user_group'];
        $data['status'] = $param['status'];
        if (!empty($param['password'])) {
            if(!preg_match('/^[a-zA-Z0-9]{4,20}$/', trim($param['password']))) {
                return resultArray(['error' => '密码格式错误', 'code' => 201]);
            }
            $data['password'] = user_md5($param['password']);
        }
        Db::table('rszh_admin_access')->where(array('user_id' => $id))->update(array('group_id' => $param['user_group']));
        $data['update_time'] = time();
        $res = $user->where(['id' => $id])->update($data);
        if ($res) {
            return resultArray(['data' => '修改用户成功']);
        }
        return resultArray(['error' => '修改失败']);
    }

    /**
     * 用户修改密码
     */
    public function changePassword($token, $old_pwd, $new_pwd)
    {
        $user = Model('User');
        $result = $user->setInfo($token, $old_pwd, $new_pwd);
        if (!$result) {
            return resultArray(['error' => $user->getError()]);
        }
        return resultArray(['data' => ['token' => $result]]);
    }

    /**
     * 更新白名单
     */
    public function whiteName($id, $status){
        $user = Model('User');
        $result = $user->updateDataById(['structure_id'=>$status], $id);
        if (!$result) {
            return resultArray(['error' => $user->getError()]);
        }
        return resultArray(['data' => '']);
    }
}
